const cacheKey = {
    // 辅助
    expiredTime: 'EXPIRED:TIME',
    expiredStartTime: 'EXPIRED:START:TIME',
    // 全局使用
    // 用户信息
    loginUserInfo: 'USER:INFO',
    // 搜索字段
    searchString: 'SEARCH:STRING',
    searchType: 'SEARCH:TYPR',
}
/**
 * 设置缓存
 *
 * @param key
 * @param value
 * @param expiredTimeMS  过期时间，单位ms
 */
const cacheSet = function (key: string, value: any, expiredTimeMS: number) {
    console.log(`cache set: key=${key} value = ${value} expiredTimeMS = ${expiredTimeMS}`)
    if (expiredTimeMS === 0 || expiredTimeMS == null) {
        localStorage.setItem(key, value)
    }
    else {
        localStorage.setItem(key, JSON.stringify(value))
        localStorage.setItem(key + cacheKey.expiredTime, `${expiredTimeMS}`)
        localStorage.setItem(key + cacheKey.expiredStartTime, `${new Date().getTime()}`)
    }
}
/**
 *  移除键
 *
 * @param key
 */
const cacheRemove = function (key: string) {
    localStorage.removeItem(key)
    localStorage.removeItem(key + cacheKey.expiredTime)
    localStorage.removeItem(key + cacheKey.expiredStartTime)
}

/**
 *  获取键
 *
 * @param key
 * @returns {*} key存在，返回对象；不存在，返回null
 */
const cacheGet = function (key: string) {
    const expiredTimeMS = localStorage.getItem(key + cacheKey.expiredTime)
    const expiredStartTime = localStorage.getItem(key + cacheKey.expiredStartTime)
    const curTime = new Date().getTime()

    const sum = Number(expiredStartTime) + Number(expiredTimeMS)

    if (sum > curTime) {
        console.log(`cache-缓存[${key}]存在！`)
        const cacheStr = localStorage.getItem(key) || ''
        return JSON.parse(cacheStr)
    }
    else {
        console.log(`cache-缓存[${key}]不存在！`)
        cacheRemove(key)
        return null
    }
}

/**
 * 对键重新更新过期时间
 *
 * @param key
 * @param expiredTimeMS  过期时间ms
 */
const cacheExpired = function (key: string, expiredTimeMS: number) {
    if (cacheGet(key) != null)
        localStorage.setItem(key + cacheKey.expiredTime, `${expiredTimeMS}`)
}
/**
 * 清除所有缓存
 */
const cacheClear = function () {
    localStorage.clear()
}

export { cacheSet, cacheGet, cacheRemove, cacheExpired, cacheClear }
